#ifndef HTTPSCONNECTION_H
#define HTTPSCONNECTION_H

#include "common.h"
#include "proxy-conn.hpp"

class httpsConnection : public boost::enable_shared_from_this<httpsConnection>
{
public:
    typedef boost::shared_ptr<httpsConnection> pointer;

    static pointer create(boost::asio::io_service& io_service, boost::asio::ssl::context& context, boost::asio::ip::tcp::resolver::iterator iendpoint_iterator, connection* iproxy_conn) {
        return pointer(new httpsConnection(io_service, context, iendpoint_iterator, iproxy_conn));
    }

    boost::asio::ssl::stream<boost::asio::ip::tcp::socket>& getSslSocket() {
        return ssocket_;
    }

private:
    httpsConnection (boost::asio::io_service& io_service, boost::asio::ssl::context& context, boost::asio::ip::tcp::resolver::iterator iendpoint_iterator, connection* iproxy_conn);

    /// Start read data of request from browser
    void start();

    void handle_handshake(const boost::system::error_code& error);
    void handle_connect(const boost::system::error_code& error,
        boost::asio::ip::tcp::resolver::iterator endpoint_iterator);
    void handle_write(const boost::system::error_code& error,
        size_t bytes_transferred);
    void handle_read(const boost::system::error_code& error,
        size_t bytes_transferred);


    void handle_handshake_noparam();

    /// Write data to the web-server
    void start_write_to_server();
    void handle_server_write(const bs::error_code& err, size_t len);

    /// Read header of data returned from the web-server
    void handle_server_read_headers(const bs::error_code& err, size_t len);

    /// Reading data from a Web server, and writing it to the browser
    void handle_browser_write(const bs::error_code& err, size_t len);
    void handle_server_read_body(const bs::error_code& err, size_t len);

    /// Close both sockets: for browser and web-server
    void shutdown();

//    boost::asio::ip::tcp::resolver::iterator endpoint_iterator;
    connection *proxy_conn;

    boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssocket_;

    bool proxy_closed;
    bool isPersistent;
    int32_t RespLen;
    int32_t RespReaded;

    boost::array<char, 8192> sbuffer;
    char reply_[33];

    std::string fURL;
    std::string fHeaders;
    std::string fNewURL;
    std::string fMethod;
    std::string fReqVersion;
    std::string fServer;
    std::string fPort;
    bool isOpened;

    std::string fReq;

    typedef boost::unordered_map<std::string,std::string> headersMap;
    headersMap reqHeaders, respHeaders;

    void parseHeaders(const std::string& h, headersMap& hm);
};

#endif // HTTPSCONNECTION_H
